package com.hou.mqacting.config;

import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * 消息队列Bean配置
 */
@Configuration
public class MessageQueueConfig {

    @Value("${rabbit.queue.string}")
    private String strQueueName;

    @Value("${rabbit.queue.object}")
    private String objQueueName;

    //配置Queue
    @Bean
    public Queue createStringQueue() {
        //boolean表示消息是否持久化
        return new Queue(strQueueName, true,false,false);
    }
    @Bean
    public Queue createObjectQueue(){
        //boolean表示消息是否持久化
        return new Queue(objQueueName,true,false,false);
    }

    //备份交互器
    @Bean
    public FanoutExchange unrouteExchange(){
        return new FanoutExchange("unrouteExchange",true,false);
    }
    //创建备份交互器与备份交互器队列
    @Bean
    public Queue unrouteQueue(){
        return new Queue("unrouteQueue",true,false,false);
    }
    //绑定备份交互器与备份队列,不需要指定key
    @Bean
    Binding bindingUnRouteExchangeMessages() {
        return BindingBuilder.bind(unrouteQueue()).to(unrouteExchange());
    }
    //创建消息队列
    @Bean
    public Queue testQueue(){
        Map<String, Object> args = new HashMap<>();
        //设置队列中的消息过期时间,为0表示除非消息立即给消费者,否则马上会被丢弃
        args.put("x-message-ttl", 6000);
        args.put("x-dead-letter-exchange", "dlxchange");//绑定死信交换器
        args.put("x-dead-letter-routing-key", "dlxKey");//需要指定死信交互器和队列绑定的key,不然会使用原队列的key,无法发送
        return new Queue("testQueue",true,false,false,args);
    }
    //创建交换器
    @Bean
    public DirectExchange exchange(){
        // 指定此交换器的备份交互器,存储没有被路由的消息
        Map<String, Object> args = new HashMap<>();
        args.put("alternate-exchange", "unrouteExchange");
        return new DirectExchange("exchange",true,false,args);
    }

    //通过指定key绑定队列与交换器
    @Bean
    Binding bindingExchangeMessages() {
        return BindingBuilder.bind(testQueue()).to(exchange()).with("routeKey");
    }




    @Bean
    public Queue expiresQueue(){
        Map<String, Object> args = new HashMap<>();
        //设置队列过期时间,程序重启后会重新计算时间
        args.put("x-expires", 20000);//20秒测试
        return new Queue("expiresQueue",true,false,false,args);
    }
}
